#!/use/bin/python
# coding=utf-8
# 主动服务-开机数/设备数-同比/环比 analysis_startup_number
# type,1为开机次数 2为开机设备量
import datetime
import pymysql
from dateutil.relativedelta import relativedelta

from dbutils.pooled_db import PooledDB


# proactive_service_conf 数据源
def getConfConnection():
    # 开发环境
    # pool = PooledDB(pymysql, 1, host='172.20.135.96', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_conf',
    #                port=3306)  # 1为连接池里的最少连接数
    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.154.103', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                db='proactive_service_conf', port=3307)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

# proactive_service_data 数据源
def getDataConnection():
    # 开发环境
    #pool = PooledDB(pymysql, 1, host='172.20.151.80', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_data',
    #                port=3306)  # 1为连接池里的最少连接数
    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.154.103', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                    db='proactive_service_data', port=3407)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

#根据月份 获取本月指定指标的 总和
#tableName 指定的报表
#columnName 指定的指标字段
#date 月份
# sqlDict 附加 的过滤条件: 如 {'type': 1}
def getSumNumByTableColumnNameAndDate(tableName,columnName,date,sqlDict):
    conn, cur = getDataConnection()
    selectNumSql = f"""
                     select sum({columnName}) from {tableName} t where 1=1   
                     """;
    if len(date) >0:
        selectNumSql = f"""{selectNumSql} and SUBSTR( t.ref_date, 1,7) = '{date}' and LENGTH(t.ref_date) = 10  """
    sqlWhere = ""
    #对日志表 中msg 数据进行过滤 {'result': 1}
    if sqlDict:
        for i, j in sqlDict.items():
            #判断value是否是数值
            if isinstance(j, int):
                sqlWhere = f""" and {i} ={j}"""
            else:
                sqlWhere = f""" and {i} ='{j}'"""
    cur.execute(selectNumSql+sqlWhere)
    #print(selectNumSql+sqlWhere);
    numResult = cur.fetchone()
    num = 0
    if numResult!= None:
        num = numResult[0]
    return num

#根据传入的SQL 返回执行SQL返回的数量
def selectNumBySql(sql):
    conn, cur = getDataConnection()
    #print(sql)
    cur.execute(sql)
    numResult = cur.fetchone()
    num = 0
    if numResult is not None:
        num = numResult[0]
    if num is None:
        return 0
    return num

#计算百分比 保留两位小数  如:34.88%
# X为分子 Y为分母
def getRateByXY(X,Y):
    rate = 0
    if(X is None or Y is None):
        return rate
    if Y != 0:
        if X > Y:
            rate = 100
        else:
            rate = round(X / Y, 4) * 100
    return rate

# 记录 数据分析-主动服务-开机数-同比/环比  analysis_startup_number   开机次数 - 每日
# type 1开机次数 2开机设备量
def insertStartupNumberDay(date,type):
    try:
        if type ==1:
            #日志文案
            logStr = '开机次数'
            #查询标志位
            sqlStr = 'count(1)'
        else:
            # 日志文案
            logStr = '开机设备量'
            # 查询标志位
            sqlStr = 'count(DISTINCT(t.active_id))'
        conn, cur = getDataConnection()
        #判断 analysis_startup_rate 表是否已经存在当天 开机率数据
        countNum = selectNumBySql(
            f"select count(1) num from analysis_startup_number t where 1=1 and t.ref_date =  '{date}' and type = {type} and dateType = 1")
        #获取 当日总体开机次数
        allNum = selectNumBySql(
            f"select {sqlStr} from log_common_service_{yyMMddDate} t where t.`key` = 'deviceOn' and  DATE_FORMAT(t.create_time, '%Y-%m-%d') = '{date}' ")
        # 获取当日早间开机 早上启动播报设备量
        zjkjNum = selectNumBySql(
            f"select {sqlStr} from log_common_service_{yyMMddDate} t where t.`key` = 'openScreen' and  DATE_FORMAT(t.create_time, '%Y-%m-%d') = '{date}'")
        # 获取 追剧提醒开机次数
        zjtxNum = selectNumBySql(
            f"select {sqlStr} from log_common_service_{yyMMddDate} t where t.`key` = 'suAutoOpenScreen' and  DATE_FORMAT(t.create_time, '%Y-%m-%d') = '{date}' ")
        # 计算因生活助手开机数
        serviceNum = zjkjNum + zjtxNum;
        # 只因生活助手触发的开机,不包括其他开机情况
        silenceNum = selectNumBySql(f"""
            select count(1) from (
                select t2.openScreenNum,t3.deviceOnNum from (
                    select count(1) openScreenNum ,t1.active_id from (
                        select * from log_common_service_{yyMMddDate} t where t.`key` = 'openScreen' and DATE_FORMAT(t.create_time, '%Y-%m-%d') ='{date}'
                        ) t1 group by t1.active_id) t2 
                    left join 
                    (select count(1) deviceOnNum,t1.active_id from (
                        select * from log_common_service_{yyMMddDate} t where t.`key` = 'deviceOn' and DATE_FORMAT(t.create_time, '%Y-%m-%d') ='{date}' and 
                        t .active_id in (select t1.active_id from log_common_service_{yyMMddDate} t1 where t1.`key` = 'openScreen' and DATE_FORMAT(t1.create_time, '%Y-%m-%d') ='{date}'
                     )) t1 group by t1.active_id ) t3
                on t2.active_id = t3.active_id 
            ) tt where tt.openScreenNum = tt.deviceOnNum 
        """)

        if countNum == 0:
            logDetail = f"新增-{date}日-{logStr}-同比/环比,总体开机数为{allNum},早间开机数为{zjkjNum},追剧提醒开机数为{zjtxNum},因生活助手开机数为{serviceNum},只因生活助手触发的开机设备量{silenceNum}"
            print(logDetail)
            # 插入 设备开机次数
            insertSql = f"""insert into analysis_startup_number(startup_num,zjkj_startup_num,zjtx_startup_num,service_startup_num,silence_startup_num,ref_date,type,dateType) 
                value({allNum},{zjkjNum},{zjtxNum},{serviceNum},{silenceNum},'{date}',{type},1)"""
            cur.execute(insertSql)
        else:
            logDetail = f"更新-{date}日-{logStr}-同比/环比,总体开机数为{allNum},早间开机数为{zjkjNum},追剧提醒开机数为{zjtxNum},因生活助手开机数为{serviceNum},只因生活助手触发的开机设备量{silenceNum}"
            print(logDetail)
            # 更新 设备开机次数
            updateSql = f"""
                update analysis_startup_number set startup_num = {allNum} ,zjkj_startup_num = {zjkjNum},zjtx_startup_num = {zjtxNum},service_startup_num = {serviceNum} ,
                    silence_startup_num = {silenceNum},update_time = now()  where  ref_date = '{date}' and type = {type} and dateType = 1
            """
            cur.execute(updateSql)
        saveLog(logDetail, date)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()

# 记录 数据分析-主动服务-开机数-同比/环比  analysis_startup_number   开机次数 -月度
# toMonthDay 当月 beforeMonthDay 上一个月 beforeYearDay 去年同一月 type 1订阅数 2订阅设备量
def insertStartupNumberMonth(toMonthDay,beforeMonthDay,beforeYearDay,type):
    try:
        if type ==1:
            #日志文案
            logStr = '开机次数'
        else:
            # 日志文案
            logStr = '开机设备量'
        conn, cur = getDataConnection()
        #判断 analysis_startup_rate 表是否已经存在当天 开机率数据
        countNum = selectNumBySql(
            f"select count(1) num from analysis_startup_number t where 1=1 and t.ref_date =  '{toMonthDay}' and type = {type} and dateType = 3")
        # 获取 月度总体开机次数
        sqlDict = {'type': type,'dateType':1}
        allNum = getSumNumByTableColumnNameAndDate('analysis_startup_number', 'startup_num', toMonthDay,sqlDict)
        # 获取 月度早间开机次数
        zjkjNum = getSumNumByTableColumnNameAndDate('analysis_startup_number', 'zjkj_startup_num', toMonthDay,sqlDict)
        # 获取 月度追剧提醒开机次数
        zjtxNum = getSumNumByTableColumnNameAndDate('analysis_startup_number', 'zjtx_startup_num', toMonthDay,sqlDict)
        # 获取 月度因生活助手开机次数
        serviceNum = getSumNumByTableColumnNameAndDate('analysis_startup_number', 'service_startup_num', toMonthDay, sqlDict)
        # 获取 月度只因生活助手开机设备量
        silenceNum = getSumNumByTableColumnNameAndDate('analysis_startup_number', 'silence_startup_num', toMonthDay,
                                                       sqlDict)
        # 获取 上一个月月总体开机次数 计算环比
        bmAllNum = selectNumBySql(
            f"select startup_num from analysis_startup_number t  where  t.ref_date = '{beforeMonthDay}' and type ={type} and dateType = 2")
        #上一个年相同月份 计算同比
        byAllNum = selectNumBySql(
            f"select startup_num from analysis_startup_number t  where  t.ref_date = '{beforeYearDay}' and type ={type} and dateType = 2" )
        # 计算开机设备数及同比环比
        monthOnMonthAll = getRateByXY(allNum-bmAllNum,bmAllNum)
        yearOnYearAll = getRateByXY(allNum-byAllNum,byAllNum)

        # 获取 上一个月月因生活助手开机次数 计算环比
        bmServiceNum = selectNumBySql(
            f"select service_startup_num from analysis_startup_number t  where  t.ref_date = '{beforeMonthDay}' and type ={type} and dateType = 3")
        # 上一个年相同月份 因生活助手开机次数 计算同比
        byServiceNum = selectNumBySql(
            f"select service_startup_num from analysis_startup_number t  where  t.ref_date = '{beforeYearDay}' and type ={type} and dateType = 3")
        # 计算因主动服务 开机设备数及同比环比
        monthOnMonthService = getRateByXY(serviceNum - bmServiceNum, bmServiceNum)
        yearOnYearService = getRateByXY(serviceNum - byServiceNum, byServiceNum)

        # 获取 上一个月月只因生活助手开机设备量 计算环比
        bmSilenceNum = selectNumBySql(
            f"select silence_startup_num from analysis_startup_number t  where  t.ref_date = '{beforeMonthDay}' and type ={type} and dateType = 3")
        # 上一个年相同月份 因生活助手开机设备量 计算同比
        bySilenceNum = selectNumBySql(
            f"select silence_startup_num from analysis_startup_number t  where  t.ref_date = '{beforeYearDay}' and type ={type} and dateType = 3")
        # 计算只因主动服务 开机设备数及同比环比
        monthOnMonthSilence = getRateByXY(silenceNum - bmSilenceNum, bmSilenceNum)
        #yearOnYearSilence = getRateByXY(silenceNum - bySilenceNum, bySilenceNum)
        yearOnYearSilence = 0

        if countNum == 0:
            logDetail = f"新增-{toMonthDay}月-{logStr}-同比/环比,总体开机数为{allNum},早间开机数为{zjkjNum},追剧提醒开机数为{zjtxNum},因生活助手开机数为{serviceNum},只因生活助手开机数为{silenceNum},总体开机上月开机数为{bmAllNum},同比为{monthOnMonthAll}," \
                        f"去年当月开机数为{byAllNum},环比为{yearOnYearAll},因生活助手开机上月开机数为{bmServiceNum},同比为{monthOnMonthService},去年当月开机数为{byServiceNum},环比为{yearOnYearService}"\
                        f"只因生活助手开机上月开机设备量为{bmSilenceNum},同比为{monthOnMonthSilence},去年当月开机设备量为{bySilenceNum},环比为{yearOnYearSilence}"
            print(logDetail)
            # 插入
            insertSql = f"""insert into analysis_startup_number(startup_num,zjkj_startup_num,zjtx_startup_num,service_startup_num,silence_startup_num,month_on_month,year_on_year,
                                service_month_on_month,service_year_on_year,silence_month_on_month,silence_year_on_year,ref_date,type,dateType) 
                value({allNum},{zjkjNum},{zjtxNum},{serviceNum},{silenceNum},{monthOnMonthAll},{yearOnYearAll},
                        {monthOnMonthService},{yearOnYearService},{monthOnMonthSilence},{yearOnYearSilence},'{toMonthDay}',{type},3)"""
            cur.execute(insertSql)
        else:
            logDetail = f"修改-{toMonthDay}月-{logStr}-同比/环比,总体开机数为{allNum},早间开机数为{zjkjNum},追剧提醒开机数为{zjtxNum},因生活助手开机数为{serviceNum},只因生活助手开机数为{silenceNum},总体开机上月开机数为{bmAllNum},同比为{monthOnMonthAll}," \
                        f"去年当月开机数为{byAllNum},环比为{yearOnYearAll},因生活助手开机上月开机数为{bmServiceNum},同比为{monthOnMonthService},去年当月开机数为{byServiceNum},环比为{yearOnYearService}" \
                        f"只因生活助手开机上月开机设备量为{bmSilenceNum},同比为{monthOnMonthSilence},去年当月开机设备量为{bySilenceNum},环比为{yearOnYearSilence}"
            print(logDetail)
            # 更新
            updateSql = f"""
                update analysis_startup_number set startup_num = {allNum} ,zjkj_startup_num = {zjkjNum},zjtx_startup_num = {zjtxNum}, service_startup_num={serviceNum},silence_startup_num={silenceNum},month_on_month = {monthOnMonthAll},year_on_year = {yearOnYearAll},
                service_year_on_year = {yearOnYearService},service_month_on_month = {monthOnMonthService},silence_month_on_month = {monthOnMonthSilence},silence_year_on_year = {yearOnYearSilence},update_time = now()  where ref_date = '{toMonthDay}' and type = {type} and dateType = 3
            """
            cur.execute(updateSql)
        saveLog(logDetail, toMonthDay)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()


# 记录 数据分析-主动服务-开机数-同比/环比  analysis_startup_number   开机次数 -月度
# toDay 当天  type 1订阅数 2订阅设备量
def insertStartupNumberWeek(toDay,type):
    try:
        if type ==1:
            #日志文案
            logStr = '开机次数'
        else:
            # 日志文案
            logStr = '开机设备量'
        conn, cur = getDataConnection()
        #判断 analysis_startup_rate 表是否已经存在当天 开机率数据
        countNum = selectNumBySql(
            f"select count(1) num from analysis_startup_number t where 1=1 and weekofyear(t.ref_date) = weekofyear('{toDay}') and type = {type}  and dateType = 2 ")
        # 获取 当周总体开机次数
        allNum = selectNumBySql(
            f"""select sum(t.startup_num) from analysis_startup_number t where t.dateType = 1 and LENGTH(t.ref_date) = 10 
              and weekofyear(t.ref_date) = weekofyear('{toDay}') and t.type = {type} """)
        # 获取 当周早间开机次数
        zjkjNum = selectNumBySql(
            f"""select sum(t.zjkj_startup_num) from analysis_startup_number t where t.dateType = 1 and LENGTH(t.ref_date) = 10 
                      and weekofyear(t.ref_date) = weekofyear('{toDay}') and t.type = {type} """)
        # 获取 当周追剧提醒开机次数
        zjtxNum = selectNumBySql(
            f"""select sum(t.zjtx_startup_num) from analysis_startup_number t where t.dateType = 1 and LENGTH(t.ref_date) = 10 
                              and weekofyear(t.ref_date) = weekofyear('{toDay}') and t.type = {type} """)
        # 获取 当周因生活助手开机次数
        serviceNum = selectNumBySql(
            f"""select sum(t.service_startup_num) from analysis_startup_number t where t.dateType = 1 and LENGTH(t.ref_date) = 10 
                                      and weekofyear(t.ref_date) = weekofyear('{toDay}') and t.type = {type} """)
        # 获取 当周只因生活助手开机设备量
        silenceNum = selectNumBySql(
            f"""select sum(t.silence_startup_num) from analysis_startup_number t where t.dateType = 1 and LENGTH(t.ref_date) = 10 
                                              and weekofyear(t.ref_date) = weekofyear('{toDay}') and t.type = {type} """)

        # 获取 上周周总体开机次数 计算环比
        bmAllNum = selectNumBySql(
            f"""
            select t.startup_num from analysis_startup_number t where t.dateType = 2  and type ={type}
                and weekofyear(t.ref_date) = weekofyear('{toDay}') -1 """)
        #上一个年相同周 计算同比
        byAllNum = selectNumBySql(
            f"""
                    select t.startup_num from analysis_startup_number t where t.dateType = 2  and type ={type}
                        and weekofyear(t.ref_date) = weekofyear('{toDay}') and year(t.ref_date) =  year('{toDay}')""")
        # 计算开机设备数及同比环比
        monthOnMonthAll = getRateByXY(allNum-bmAllNum,bmAllNum)
        yearOnYearAll = getRateByXY(allNum-byAllNum,byAllNum)

        # 获取 上一周周因生活助手开机次数 计算环比
        bmServiceNum = selectNumBySql(
            f"""
                    select t.service_startup_num from analysis_startup_number t where t.dateType = 2  and type ={type}
                        and weekofyear(t.ref_date) = weekofyear('{toDay}') -1 """)
        # 上一个年相同周 因生活助手开机次数 计算同比
        byServiceNum = selectNumBySql(
            f"""
                            select t.service_startup_num from analysis_startup_number t where t.dateType = 2  and type ={type}
                                and weekofyear(t.ref_date) = weekofyear('{toDay}') and year(t.ref_date) =  year('{toDay}') - 1""")
        # 计算因主动服务 开机设备数及同比环比
        monthOnMonthService = getRateByXY(serviceNum - bmServiceNum, bmServiceNum)
        yearOnYearService = getRateByXY(serviceNum - byServiceNum, byServiceNum)

        # 获取 上一周只因生活助手的周开机设备量 计算环比
        bmSilenceNum = selectNumBySql(
            f"""
                            select t.silence_startup_num from analysis_startup_number t where t.dateType = 2  and type ={type}
                                and weekofyear(t.ref_date) = weekofyear('{toDay}') -1 """)
        # 上一个年相同周 因生活助手开机设备量 计算同比
        bySilenceNum = selectNumBySql(
            f"""
                                    select t.silence_startup_num from analysis_startup_number t where t.dateType = 2  and type ={type}
                                        and weekofyear(t.ref_date) = weekofyear('{toDay}') and year(t.ref_date) =  year('{toDay}') - 1""")
        # 计算只因主动服务 开机设备数及同比环比
        monthOnMonthSilence = getRateByXY(silenceNum - bmSilenceNum, bmSilenceNum)
        yearOnYearSilence = getRateByXY(silenceNum - bySilenceNum, bySilenceNum)

        if countNum == 0:
            logDetail = f"新增-{toDay}周-{logStr}-同比/环比,总体开机数为{allNum},早间开机数为{zjkjNum},追剧提醒开机数为{zjtxNum},因生活助手开机数为{serviceNum},只因生活助手开机数为{silenceNum},总体开机上周开机数为{bmAllNum},同比为{monthOnMonthAll}," \
                        f"去年当周开机数为{byAllNum},环比为{yearOnYearAll},因生活助手开机上周开机数为{bmServiceNum},同比为{monthOnMonthService},去年当周开机数为{byServiceNum},环比为{yearOnYearService}"\
                        f"只因生活助手开机上周开机设备量为{bmSilenceNum},同比为{monthOnMonthSilence},去年当周开机设备量为{bySilenceNum},环比为{yearOnYearSilence}"
            print(logDetail)
            # 插入
            insertSql = f"""insert into analysis_startup_number(startup_num,zjkj_startup_num,zjtx_startup_num,service_startup_num,silence_startup_num,month_on_month,year_on_year,
                                service_month_on_month,service_year_on_year,silence_month_on_month,silence_year_on_year,ref_date,type,dateType) 
                value({allNum},{zjkjNum},{zjtxNum},{serviceNum},{silenceNum},{monthOnMonthAll},{yearOnYearAll},
                        {monthOnMonthService},{yearOnYearService},{monthOnMonthSilence},{yearOnYearSilence},'{toDay}',{type},2)"""
            cur.execute(insertSql)
        else:
            logDetail = f"修改-{toDay}周-{logStr}-同比/环比,总体开机数为{allNum},早间开机数为{zjkjNum},追剧提醒开机数为{zjtxNum},因生活助手开机数为{serviceNum},只因生活助手开机数为{silenceNum},总体开机上周开机数为{bmAllNum},同比为{monthOnMonthAll}," \
                        f"去年当周开机数为{byAllNum},环比为{yearOnYearAll},因生活助手开机上周开机数为{bmServiceNum},同比为{monthOnMonthService},去年当周开机数为{byServiceNum},环比为{yearOnYearService}" \
                        f"只因生活助手开机上周开机设备量为{bmSilenceNum},同比为{monthOnMonthSilence},去年当周开机设备量为{bySilenceNum},环比为{yearOnYearSilence}"
            print(logDetail)
            # 更新
            updateSql = f"""
                update analysis_startup_number set startup_num = {allNum} ,zjkj_startup_num = {zjkjNum},zjtx_startup_num = {zjtxNum}, service_startup_num={serviceNum},silence_startup_num={silenceNum},month_on_month = {monthOnMonthAll},year_on_year = {yearOnYearAll},
                service_year_on_year = {yearOnYearService},service_month_on_month = {monthOnMonthService},silence_month_on_month = {monthOnMonthSilence},silence_year_on_year = {yearOnYearSilence},update_time = now()  where weekofyear(ref_date) = weekofyear('{toDay}') and type = {type} and dateType = 2
            """
            cur.execute(updateSql)
        saveLog(logDetail, toDay)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()

# 获取当前日期
def todayYMD():
    today = datetime.datetime.now()-1
    # 获取想要的日期的时间
    re_date = (today).strftime('%Y-%m-%d')
    return re_date


# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m-%d')
    return re_date

# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getMonthdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m')
    return re_date

# 获取上一个月
def getBeforeMonth(d):
    today = datetime.datetime.now()
    re_date = (today + relativedelta(months=-d)).strftime("%Y-%m")
    return re_date

# 获取上一个年当月
def getBeforeYear():
    today = datetime.datetime.now()
    re_date = (today + relativedelta(years=-1)).strftime("%Y-%m")
    return re_date

#如 2022年12月13号 获取 221213 作为分表后缀
def getdateyyMMdd(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y%m%d')
    re_date = re_date[2:]
    return re_date

def saveLog(detail,ref_date):
    try:
        conn, cur = getDataConnection()
        jobId = 52
        jobName = '核心指标-生活助手-开机数/设备数及同比/环比	'
        tableName = 'analysis_startup_number'
        # 插入日志表
        saveLogSql = """insert into log_xxljob_analysis (job_id,job_name,detail,table_name,ref_date) 
                value(%s,'%s','%s','%s','%s')""" % (jobId,jobName,detail,tableName,ref_date)
        cur.execute(saveLogSql)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()

if __name__ == '__main__':
    d = 1
    today = getdate(d)
    yyMMddDate = getdateyyMMdd(d)
    toMonthDay = getMonthdate(d)
    beforeMonthDay = getBeforeMonth(1)
    beforeYearDay = getBeforeYear()
    print(f"{today}日期,执行<开机数/设备数-同比/环比>报表")
    insertStartupNumberDay(today,1)
    insertStartupNumberDay(today,2)
    insertStartupNumberMonth(toMonthDay,beforeMonthDay,beforeYearDay,1)
    insertStartupNumberMonth(toMonthDay, beforeMonthDay, beforeYearDay,2)
    insertStartupNumberWeek(today, 1)
    insertStartupNumberWeek(today, 2)


